package io.terminus.paas.profiler.model

import com.alibaba.dubbo.common.Constants
import com.alibaba.dubbo.common.URL

/**
 * Created by gengrong on 16/3/15.
 */
class Route {

    var id: Long? = null

    var parentId: Long = 0 //默认为0

    var name: String? = null

    var service: String? = null

    var rule: String? = null

    var matchRule: String? = null

    var filterRule: String? = null

    var priority: Int = 0

    var username: String? = null

    var enabled: Boolean = false

    var force: Boolean = false

    var children: List<Route>? = null

    fun toUrl(): URL {
        var group: String? = null
        var version: String? = null
        var path = service!!
        var i = path.indexOf("/")
        if (i > 0) {
            group = path.substring(0, i)
            path = path.substring(i + 1)
        }
        i = path.lastIndexOf(":")
        if (i > 0) {
            version = path.substring(i + 1)
            path = path.substring(0, i)
        }
        return URL.valueOf(Constants.ROUTE_PROTOCOL + "://" + Constants.ANYHOST_VALUE + "/" + path
                + "?" + Constants.CATEGORY_KEY + "=" + Constants.ROUTERS_CATEGORY
                + "&router=condition&runtime=false&enabled=" + enabled + "&priority=" + priority + "&force=" + force + "&dynamic=false"
                + "&name=" + name + "&" + Constants.RULE_KEY + "=" + URL.encode(matchRule + " => " + filterRule)
                + if (group == null) "" else "&" + Constants.GROUP_KEY + "=" + group
                + if (version == null) "" else "&" + Constants.VERSION_KEY + "=" + version)
    }

    fun setRuleStr(rule: String) {
        this.rule = rule
        val rules = rule.split(" => ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        if (rules.size != 2) {
            throw IllegalArgumentException("Illegal Route Condition Rule")
        }
        this.matchRule = rules[0]
        this.filterRule = rules[1]
    }
}